package com.gzs.space.controller;


import com.gzs.space.entity.FdfsFile;
import com.gzs.space.entity.User;
import com.gzs.space.feign.TestFeign;
import com.gzs.space.response.CommonResponse;
import com.gzs.space.service.UploadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author GZS
 * @date 2022年04月16日
 */
@RequestMapping("/uploadFile")
@RestController
public class UploadFileController {

	@Autowired
	private UploadFileService uploadFileService;
	/**
	 * 保存到本地盘
	 * 每天创建一个子文件夹
	 * 先判断有没有相同文件夹，没有先创建
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	public CommonResponse upload(@RequestParam("file") MultipartFile file){
		if (uploadFileService.uploadFile(file)){
			return CommonResponse.ok("上传成功！");
		}
		return CommonResponse.fail("上传失败！");
	}

	/**
	 * 上传文件列表
	 * @param model
	 * @return
	 */
	@GetMapping("/listFile")
	public CommonResponse listFile(Model model){
		List<FdfsFile> findAll = uploadFileService.findAll();
		return CommonResponse.ok(findAll);
	}

	/**
	 * 删除文件
	 * @param id
	 * @return
	 */
	@DeleteMapping("/deleteFile")
	public CommonResponse deleteFile(Integer id){
		if (uploadFileService.deleteFile(id)){
			return CommonResponse.ok("删除成功！");
		}
		return CommonResponse.fail("删除失败！");
	}

	/**
	 * 用响应输出流，向客户端写文件
	 * @param id 要下载的文件
	 * @param response 响应对象
	 */
	@RequestMapping("/download")
	public void downLoad(Integer id, HttpServletResponse response){
		uploadFileService.downLoad(id,response);
	}

	@RequestMapping("/ok")
	public String ok(){
		return "ok";
	}
	@RequestMapping("/fail")
	public String fail(){
		return "fail";
	}

	@RequestMapping("/")
	public String toIndex(){
		return "index";
	}

	@Autowired
	private TestFeign testFeign;

	@GetMapping("/users")
	public CommonResponse users(){
		List<User> users = testFeign.allUser();
		return CommonResponse.ok(users);
	}
}
